//
//  EBHNetWorkingManager.m
//  EBHDoctor
//
//  Created by 黄德玉 on 2019/11/16.
//  Copyright © 2019 DCloud. All rights reserved.
//



#import "EBHNetWorkingManager.h"
#import "AFNetworking.h"

@implementation EBHNetWorkingManager


+ (void)queryWithPath:(NSString *)path pars:(id)pars callback:(void (^)(NSError * _Nonnull, id _Nonnull))callback{
    [self queryWithPath:path pars:pars method:@"GET" callback:callback];
}

+ (void)queryWithPath:(NSString *)path pars:(id)pars method:(NSString *)method callback:(void (^)(NSError * _Nonnull, id _Nonnull))callback{
    __block NSString * urlStr = [NSString stringWithFormat:@"%@%@",BASE_URL,path];
    if ([method isEqualToString:@"GET"]) {
        urlStr = [NSString stringWithFormat:@"%@%@?",BASE_URL,path];
        NSDictionary * dic = pars;
        [dic enumerateKeysAndObjectsUsingBlock:^(id  _Nonnull key, id  _Nonnull obj, BOOL * _Nonnull stop) {
            urlStr = [NSString stringWithFormat:@"%@%@=%@&",urlStr,key,obj];
        }];
        urlStr = [urlStr substringToIndex:urlStr.length - 1];
    }
    
    NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlStr]];
    if (![method isEqualToString:@"GET"]) {
        request.HTTPBody = [NSJSONSerialization dataWithJSONObject:pars options:NSJSONWritingPrettyPrinted error:nil];
        [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    } else {
        [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    }
    NSString * token =  [EBHUserManager sharedManager].userInfo.token;
    if (token) {
         [request setValue:token forHTTPHeaderField:@"x-token"];
    }
    request.HTTPMethod = method;
     NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
     AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
    NSURLSessionTask * task = [manager dataTaskWithRequest:request completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
        if (callback) {
            NSInteger status = [[responseObject objectForKey:@"status"] integerValue];
            id data = [responseObject objectForKey:@"data"];
            callback(error,data);
        }
    }];
    [task resume];
}



@end
